package com.yuanian.timingwheel.model.timingwheel.helper;

import com.yuanian.timingwheel.config.JobConfig;
import com.yuanian.timingwheel.respository.po.LivingServerEntity;
import com.yuanian.timingwheel.respository.po.TaskEntity;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class DbHelper {

    /**
     * 获取当前23:59:59之前的任务
     * @return
     */
    public static List<TaskEntity> getEndOfDayTask() {
        return TaskEntity.getEndOfDayTask();
    }

    public static void updateLivingServer(Long id, Date lastRespondTime, long delayCnt) {
        LivingServerEntity.updateLivingServer(id, lastRespondTime, delayCnt);
    }

    /**
     * 锁住当前的任务加载
     */
    public static Long lockDay(LockedAction lockedAction) {

        Connection conn = null;
        Boolean connAutoCommit = null;
        PreparedStatement preparedStatement = null;
        try {
            conn = JobConfig.getInstance().getDataSource().getConnection();
            connAutoCommit = conn.getAutoCommit();
            conn.setAutoCommit(false);

            preparedStatement = conn.prepareStatement(  "select * from TP_TW_LOCK where lock_name = 'schedule_lock' for update" );
            preparedStatement.execute();

            //存在正在运行的机器
            if (LivingServerEntity.existLivingServer()) {
                return null;
            }
            //执行任务
            lockedAction.action();

            return LivingServerEntity.createLivingServer();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {

            // commit
            if (conn != null) {
                try {
                    conn.commit();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                try {
                    conn.setAutoCommit(connAutoCommit);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            // close PreparedStatement
            if (null != preparedStatement) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 加锁后需要执行的业务逻辑
     */
    public interface LockedAction {
        void action();
    }

}
